package 基础篇.线程同步.同步锁;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author IBM CHEN ZHI KAN
 * @create 2018/7/28
 */
public class Account {
  private String accountNo;//账户编号
  private double balance;//账户余额
  private final ReentrantLock lock=new ReentrantLock();
  public Account(String accountNo, double balance) {
    this.accountNo = accountNo;
    this.balance = balance;
  }

  public String getAccountNo() {
    return accountNo;
  }

  public void setAccountNo(String accountNo) {
    this.accountNo = accountNo;
  }

  public double getBalance() {
    return balance;
  }

  public void setBalance(double balance) {
    this.balance = balance;
  }

  public synchronized void draw(double drawAmount){
    //加锁
    lock.lock();
    try {
      if(balance>=drawAmount){
          System.out.println("取钱成功，吐出钞票");
          try{
            Thread.sleep(1000l);
          }catch (Exception e){
            e.printStackTrace();
          }
          setBalance(getBalance()-drawAmount);
          System.out.println("余额为："+getBalance());
        }else{
          System.out.println("余额已取完");
      }
    }catch (Exception e){
      e.printStackTrace();
    }finally {
      //释放锁
      lock.unlock();
    }
  }
}
